<template>
<div>
  <canvas class="mycanvas" :ref="'canvas' + id" :width="width" :height="height" tabindex="0"></canvas>
</div>
</template>

<script>
export default {
  name: 'canvas',
  props: {
  },
  data(){
    return {
      id:1,//使用时间戳作为每个上传控件的唯一标准
      width:320,
      height:320
    }
  },
  methods:{

  },
  mounted(){
    //获取canvas元素
    var canvas = this.$refs['canvas' + this.id]
    //获取画布的宽度和高度
    const canvasWidth = canvas.clientWidth
    const canvasHeight = canvas.clientHeight
     // 在画布上移动的方块的长宽
    const [rectWidth, rectHeight] = [40, 40]
    // 方块的横纵坐标
    let [rectX, rectY] = [0, 0]
    canvas.width = canvasWidth
    canvas.height = canvasHeight
    let context = canvas.getContext('2d')
    context.fillStyle = 'red'
    rectX = (canvasWidth - rectWidth) / 2
    rectY = (canvasHeight - rectHeight) / 2
    context.fillRect(rectX, rectY, rectWidth, rectHeight)
    // canvas元素上监听键盘输入事件
    canvas.addEventListener('keydown', doKeyDown, true)
    canvas.focus() // 让canvas聚焦
    function clearCanvas() {
      context.clearRect(0, 0, canvasWidth, canvasHeight)
    }
    function doKeyDown(e) {
      // 获取keyCode
      const keyCode = e.keyCode ? e.keyCode : e.which
      // 向上箭头 / w，让纵坐标向上移动10
      if (keyCode === 38 || keyCode === 87) {
        clearCanvas()
        rectY -= 10
        if (rectY < 0) {
          rectY = 0
        }
        context.fillRect(rectX, rectY, rectWidth, rectHeight)
      }
      // 向下箭头 / s，让纵坐标向下移动10
      if (keyCode === 40 || keyCode === 83) {
        clearCanvas()
        rectY += 10
        if (rectY > canvasHeight - rectHeight) {
          rectY = canvasHeight - rectHeight
        }
        context.fillRect(rectX, rectY, rectWidth, rectHeight)
      }

      // 向左箭头 / a，让纵坐标向左移动10
      if (keyCode === 37 || keyCode === 65) {
        clearCanvas()
        rectX -= 10
        if (rectX < 0) {
          rectX = 0
        }
        context.fillRect(rectX, rectY, rectWidth, rectHeight)
      }

      // 向右箭头 / d，让纵坐标向右移动10
      if (keyCode === 39 || keyCode === 68) {
        clearCanvas()
        rectX += 10
        if (rectX > canvasWidth - rectWidth) {
          rectX = canvasWidth - rectWidth
        }
        context.fillRect(rectX, rectY, rectWidth, rectHeight)
      }
    }		  

  }

}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
  .mycanvas{
    margin: 0 auto;
    background: #f1f1f1;
  }
</style>